<template>
  <div class="map-container">
    <div class="map-header">
      <button 
        v-if="currentMapLevel === 'city'" 
        @click="goBack" 
        class="back-button"
      >
        ← 返回省级
      </button>
      <div class="map-title">{{ currentMapName }}</div>
    </div>
    <div ref="mapRef" class="map-chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

interface Props {
  initialMapLevel?: 'province' | 'city'
  initialMapName?: string
}

const props = withDefaults(defineProps<Props>(), {
  initialMapLevel: 'province',
  initialMapName: '广东省'
})

const emit = defineEmits<{
  mapLevelChange: [level: 'province' | 'city']
  cityChange: [cityName: string]
}>()

const mapRef = ref<HTMLElement>()
const currentMapLevel = ref(props.initialMapLevel)
const currentMapName = ref(props.initialMapName)
let mapInstance: echarts.ECharts | null = null

const cityAdcodeMap: Record<string, string> = {
  广州市: '440100',
  深圳市: '440300',
  珠海市: '440400',
  汕头市: '440500',
  佛山市: '440600',
  韶关市: '440200',
  湛江市: '440800',
  肇庆市: '441200',
  江门市: '440700',
  茂名市: '440900',
  惠州市: '441300',
  梅州市: '441400',
  汕尾市: '441500',
  河源市: '441600',
  阳江市: '441700',
  清远市: '441800',
  东莞市: '441900',
  中山市: '442000',
  潮州市: '445100',
  揭阳市: '445200',
  云浮市: '445300',
}

const initGuangdongMap = async () => {
  if (!mapRef.value) return

  mapRef.value.innerHTML = '<div style="color:white;text-align:center;padding-top:20px">正在加载地图数据...</div>'

  try {
    mapRef.value.style.display = 'block'
    mapRef.value.style.width = '100%'
    mapRef.value.style.height = '100%'
    mapRef.value.style.minHeight = '400px'

    if (mapRef.value.clientWidth === 0 || mapRef.value.clientHeight === 0) {
      setTimeout(initGuangdongMap, 200)
      return
    }

    if (mapInstance && !mapInstance.isDisposed()) {
      mapInstance.dispose()
    }

    mapInstance = echarts.init(mapRef.value)

    const response = await fetch('https://geo.datav.aliyun.com/areas/bound/440000_full.json')
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
    const provinceData = await response.json()

    echarts.registerMap('guangdong', provinceData)
    renderProvinceMap()
  } catch (error) {
    console.error('地图初始化失败:', error)
    if (mapRef.value) {
      mapRef.value.innerHTML = '<div style="color:red;text-align:center;padding-top:20px">地图加载失败，请刷新重试</div>'
    }
  }
}

const renderProvinceMap = () => {
  if (!mapInstance) return

  const mapOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>GDP: {c}亿元',
      backgroundColor: 'rgba(10, 25, 41, 0.9)',
      borderColor: '#4a90e2',
      textStyle: { color: '#ffffff' },
    },
    visualMap: {
      min: 100,
      max: 4000,
      left: 'right',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#e0f3ff', '#4a90e2', '#1e5799'],
      },
      textStyle: {
        color: '#ffffff',
        fontSize: 12,
      },
      itemWidth: 20,
      itemHeight: 100,
    },
    series: [
      {
        name: 'GDP',
        type: 'map',
        map: 'guangdong',
        roam: true,
        zoom: 1,
        emphasis: {
          label: {
            show: true,
            color: '#ffffff',
            fontSize: 12,
          },
          itemStyle: {
            areaColor: '#357abd',
            borderColor: '#4a90e2',
            borderWidth: 2,
          },
        },
        data: [
          { name: '广州市', value: 2800 },
          { name: '深圳市', value: 3200 },
          { name: '珠海市', value: 380 },
          { name: '汕头市', value: 310 },
          { name: '佛山市', value: 1200 },
          { name: '韶关市', value: 180 },
          { name: '湛江市', value: 320 },
          { name: '肇庆市', value: 240 },
          { name: '江门市', value: 350 },
          { name: '茂名市', value: 340 },
          { name: '惠州市', value: 480 },
          { name: '梅州市', value: 150 },
          { name: '汕尾市', value: 120 },
          { name: '河源市', value: 140 },
          { name: '阳江市', value: 200 },
          { name: '清远市', value: 180 },
          { name: '东莞市', value: 1100 },
          { name: '中山市', value: 380 },
          { name: '潮州市', value: 140 },
          { name: '揭阳市', value: 240 },
          { name: '云浮市', value: 110 },
        ],
        itemStyle: {
          areaColor: 'rgba(30, 58, 95, 0.6)',
          borderColor: '#4a90e2',
          borderWidth: 1,
        },
        label: {
          show: true,
          color: '#ffffff',
          fontSize: 10,
        },
        selectedMode: 'single',
      },
    ],
  }

  mapInstance.setOption(mapOption)

  mapInstance.off('click')
  mapInstance.on('click', (params: any) => {
    if (params.componentType === 'series' && currentMapLevel.value === 'province') {
      const cityName = params.name
      drillDownToCity(cityName)
    }
  })
}

const drillDownToCity = async (cityName: string) => {
  if (!mapInstance) return

  try {
    const adcode = cityAdcodeMap[cityName]
    if (!adcode) {
      console.log(`${cityName}的地图数据暂未提供`)
      return
    }

    const response = await fetch(`https://geo.datav.aliyun.com/areas/bound/${adcode}_full.json`)
    if (!response.ok) throw new Error(`Failed to fetch ${cityName} data`)
    const cityData = await response.json()

    const mapName = cityName.replace('市', '')
    echarts.registerMap(mapName, cityData)

    currentMapLevel.value = 'city'
    currentMapName.value = cityName
    emit('mapLevelChange', 'city')
    emit('cityChange', cityName)

    if (mapRef.value) {
      mapRef.value.style.display = 'block'
      mapRef.value.style.width = '100%'
      mapRef.value.style.height = '100%'
      mapRef.value.style.minHeight = '400px'
    }

    if (mapInstance && !mapInstance.isDisposed()) {
      mapInstance.dispose()
    }

    mapInstance = echarts.init(mapRef.value)
    renderDistrictMap(mapName, cityName)
  } catch (error) {
    console.error(`加载${cityName}地图数据失败:`, error)
  }
}

const renderDistrictMap = (mapName: string, cityName: string) => {
  if (!mapInstance) return

  const districtData = getDistrictData(cityName)

  const mapOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>GDP: {c}亿元',
      backgroundColor: 'rgba(10, 25, 41, 0.9)',
      borderColor: '#4a90e2',
      textStyle: { color: '#ffffff' },
    },
    visualMap: {
      min: 50,
      max: 800,
      left: 'right',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: ['#e0f3ff', '#4a90e2', '#1e5799'],
      },
      textStyle: {
        color: '#ffffff',
        fontSize: 12,
      },
      itemWidth: 20,
      itemHeight: 100,
    },
    series: [
      {
        name: 'GDP',
        type: 'map',
        map: mapName,
        roam: true,
        zoom: 1,
        emphasis: {
          label: {
            show: true,
            color: '#ffffff',
            fontSize: 12,
          },
          itemStyle: {
            areaColor: '#357abd',
            borderColor: '#4a90e2',
            borderWidth: 2,
          },
        },
        data: districtData,
        itemStyle: {
          areaColor: 'rgba(30, 58, 95, 0.6)',
          borderColor: '#4a90e2',
          borderWidth: 1,
        },
        label: {
          show: true,
          color: '#ffffff',
          fontSize: 10,
        },
        selectedMode: 'single',
      },
    ],
  }

  mapInstance.setOption(mapOption)
}

const getDistrictData = (cityName: string) => {
  const districtDataMap: Record<string, any[]> = {
    广州市: [
      { name: '天河区', value: 600 },
      { name: '越秀区', value: 400 },
      { name: '海珠区', value: 350 },
      { name: '荔湾区', value: 300 },
      { name: '白云区', value: 280 },
      { name: '黄埔区', value: 320 },
      { name: '番禺区', value: 380 },
      { name: '花都区', value: 250 },
      { name: '南沙区', value: 200 },
      { name: '从化区', value: 150 },
      { name: '增城区', value: 220 },
    ],
    深圳市: [
      { name: '南山区', value: 700 },
      { name: '福田区', value: 650 },
      { name: '罗湖区', value: 400 },
      { name: '宝安区', value: 550 },
      { name: '龙岗区', value: 480 },
      { name: '龙华区', value: 350 },
      { name: '坪山区', value: 200 },
      { name: '光明区', value: 180 },
      { name: '盐田区', value: 120 },
    ],
  }

  return districtDataMap[cityName] || []
}

const goBack = () => {
  currentMapLevel.value = 'province'
  currentMapName.value = '广东省'
  emit('mapLevelChange', 'province')
  initGuangdongMap()
}

onMounted(() => {
  setTimeout(() => {
    initGuangdongMap()
  }, 300)
})

onUnmounted(() => {
  if (mapInstance && !mapInstance.isDisposed()) {
    mapInstance.dispose()
  }
})
</script>

<style scoped>
.map-container {
  background: rgba(30, 58, 95, 0.6);
  border: 1px solid rgba(74, 144, 226, 0.3);
  border-radius: 8px;
  padding: 20px;
  backdrop-filter: blur(10px);
  flex: 1;
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.map-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 15px;
}

.back-button {
  background: rgba(74, 144, 226, 0.8);
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(74, 144, 226, 1);
}

.map-title {
  font-size: 16px;
  color: #4a90e2;
  font-weight: 500;
}

.map-chart {
  flex: 1;
  width: 100%;
  overflow: hidden;
}
</style>